package com.jinxin.platform.cddatadict.controller;


import com.jinxin.platform.base.api.annotation.APCOSApi;
import com.jinxin.platform.base.api.annotation.APCOSApiOperation;
import com.jinxin.platform.base.api.constant.APCOSApiConstans;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cddatadict.pojo.domains.DataDictItem;
import com.jinxin.platform.cddatadict.pojo.domains.DataDictType;
import com.jinxin.platform.cddatadict.pojo.entity.ResultEntity;
import com.jinxin.platform.cddatadict.service.SysDictItemService;
import com.jinxin.platform.cddatadict.service.SysDictTypeService;
import com.jinxin.platform.cddatadict.utils.DateUtil;
import com.jinxin.platform.cddatadict.utils.IdWorker;
import com.jinxin.platform.cddatadict.utils.Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO(简述该类的作用)
 * @Classn: DictController
 * @author blue
 * @date 2020-05-16
 */
@APCOSApi(value = "字典接口", developers = {"那个男人"}, description = "字典接口")
@RestController
public class CddatadictDictController {
	@Autowired
	private SysDictTypeService dictTypeService;
	@Autowired
	private SysDictItemService dictItemService;
	@Resource
	private IdWorker idWorker;

	/**
	 * 
	 * TODO(简述该方法的作用)獲取所有的字典類型
	 * @method getType
	 * @return ResultEntity
	 * @return
	 */
	@APCOSApiOperation(value = "获取字典类型列表", developers = {"lingnan"}, description = "获取字典类型列表",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/type")
	public ResultEntity getType() {
		return new ResultEntity("","",dictTypeService.list(new HashMap()));
	}

	@APCOSApiOperation(value = "导入字典", developers = {"lingnan"}, description = "导入字典",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("/cddatadict/type/upload")
	public JsonResult upload(MultipartFile file) {
		return dictTypeService.importDict(file);
	}

	@APCOSApiOperation(value = "导入字典2", developers = {"lingnan"}, description = "导入字典2",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("/cddatadict/type/upload2")
	public JsonResult upload2(MultipartFile file) {
		return dictTypeService.importDict2(file);
	}

	@APCOSApiOperation(value = "导出字典", developers = {"lingnan"}, description = "导出字典",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/type/export")
	public void exportProduct(HttpServletResponse response) {
		String fileName = DateUtil.getCurrentYMDHMS()+".json";
		dictTypeService.exportDict(response,fileName);
	}

	@APCOSApiOperation(value = "导出字典2", developers = {"lingnan"}, description = "导出字典2",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/type/export2")
	public void exportProduct2(HttpServletResponse response) {
		String fileName = DateUtil.getCurrentYMDHMS()+".json";
		dictTypeService.exportDict2(response,fileName);
	}

	@APCOSApiOperation(value = "全部删除", developers = {"lingnan"}, description = "全部删除",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/deleteAll")
	public JsonResult deleteAll() {
		return dictTypeService.deleteAll();
	}

	/**
	 * 
	 * TODO(简述该方法的作用)獲取所有的字典類型
	 * @method getType
	 * @return ResultEntity
	 * @return
	 */
	@APCOSApiOperation(value = "获取字典类型", developers = {"lingnan"}, description = "获取字典类型",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/type/id")
	public ResultEntity getTypeById(String typeId) {
		DataDictType resultEntity = dictTypeService.selectByKey(typeId);
		return new ResultEntity("","OK",resultEntity);
	}
	
	/**
	 * 
	 * TODO(简述该方法的作用)新增字典類型
	 * @method addType
	 * @return ResultEntity
	 * @param typeName
	 * @param typeDesc
	 * @return
	 */
	@APCOSApiOperation(value = "新增字段类型", developers = {"lingnan"}, description = "新增字段类型",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("cddatadict/type/add")
	public ResultEntity addType(String typeName, String typeDesc) {
		//校驗新增類型是否存在
		HashMap param = new HashMap();
		param.put("typeName", typeName);
		DataDictType resultEntity = dictTypeService.selectOne(param);
		if(resultEntity != null) {
			return new ResultEntity("","isExist");
		}
		//新增字典類型
		DataDictType entity = new DataDictType();
		entity.setId(idWorker.nextId()+"");
		entity.setTypeName(typeName);
		entity.setTypeReadme(typeDesc);
		entity.setEnableType("yes");
		entity.setCreateTime(LocalDateTime.now());
		dictTypeService.insert(entity);
		return new ResultEntity("","OK");
	}
	
	/**
	 * 
	 * TODO(简述该方法的作用)根據字典類型ID，更新字典類型
	 * @method updateType
	 * @return ResultEntity
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	@APCOSApiOperation(value = "更新字段类型", developers = {"lingnan"}, description = "更新字段类型",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("cddatadict/type/update")
	public ResultEntity updateType(DataDictType dto) throws Exception {
		//校驗新增的字段名是否存在
		HashMap param = new HashMap();
		param.put("typeName", dto.getTypeName());
		DataDictType resultEntity = dictTypeService.selectOne(param);
		if(resultEntity != null && !resultEntity.getId().equals(dto.getId())) {
			return new ResultEntity("","nameIsExist");
		}
		//更新字典類型
		DataDictType entity = new DataDictType();
		BeanUtils.copyProperties(dto, entity);
		entity.setUpdateTime(LocalDateTime.now());
		dictTypeService.updateByKey(entity);
		return new ResultEntity("","OK");
	}
	
	/**
	 * 
	 * TODO(简述该方法的作用)根據字典類型ID刪除字典類型
	 * @method deleteType
	 * @return ResultEntity
	 * @param typeId
	 * @return
	 */
	@APCOSApiOperation(value = "删除类型", developers = {"lingnan"}, description = "删除类型",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("/cddatadict/type/delete")
	public ResultEntity deleteType(String typeId) {
		dictTypeService.deleteByKey(typeId);
		return new ResultEntity("","OK");
	}
	
	/**
	 * 
	 * TODO(简述该方法的作用)根据字典类型名称获取字典值
	 * @method getDicts
	 * @return ResultEntity
	 * @return
	 */
	@APCOSApiOperation(value = "分页查询一级字典项", developers = {"lingnan"}, description = "分页查询一级字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/dicts")
	public Map<String,Object> getDictsByType(String dictType, int page, int rows) {
		Map<String,Object> resultMap = new HashMap<>();
		HashMap param = new HashMap();
		param.put("dictType", dictType);
		param.put("page", page);
		param.put("limit", rows);
		param.put("dictLevel", 1);//只显示一级的
		resultMap.put("code",0);
		resultMap.put("msg","");
		resultMap.put("count",dictItemService.listPageCount(param));
		resultMap.put("data",dictItemService.listPage(param));
		return resultMap;
	}

	@APCOSApiOperation(value = "查询下级字典项", developers = {"lingnan"}, description = "查询下级字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/dicts2")
	public Map<String,Object> getDictsByType2(String dictType) {
		Map<String,Object> resultMap = new HashMap<>();
		HashMap param = new HashMap();
//		if(StringUtils.isEmpty(dictType)){
//			param.put("dictLevel", 1);//只显示一级的
//		}
		param.put("dictType", dictType);
		resultMap.put("code",0);
		resultMap.put("msg","");
		List<DataDictItem> list = dictItemService.list(param);
		for (DataDictItem dictItem : list) {
			HashMap param2 = new HashMap();
			param2.put("dictType",dictItem.getId());
			int count = dictItemService.listPageCount(param2);
			dictItem.setHaveChild(count>0);
		}
		resultMap.put("count", list.size());
		resultMap.put("data", list);
		return resultMap;
	}

	/**
	 * 
	 * TODO(简述该方法的作用)根据字典类型名称获取字典值
	 * @method getDicts
	 * @return ResultEntity
	 * @return
	 */
	@APCOSApiOperation(value = "根据字典类型查询字典项", developers = {"lingnan"}, description = "根据字典类型查询字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/dicts/dictType")
	public ResultEntity getDictsType(String dictType) {
		if(dictType == null || dictType.isEmpty()) {
			return new ResultEntity("","fail");
		}
		HashMap param = new HashMap();
		param.put("typeName", dictType);
		String typeId = dictTypeService.selectOne(param).getId();
		HashMap param2 = new HashMap();
		param2.put("dictType", typeId);
		return new ResultEntity("","OK",dictItemService.list(param2));
	}

	@APCOSApiOperation(value = "根据字典类型查询字典项", developers = {"lingnan"}, description = "根据字典类型查询字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/dicts/dictType2")
	public ResultEntity getDictsType2(String key, String type, String typeId) {
		// 直接通过id查询
		if(!StringUtils.isEmpty(typeId)){
			HashMap param = new HashMap();
			param.put("dictType", typeId);
			return new ResultEntity("","OK",dictItemService.list(param));
		}else if(!StringUtils.isEmpty(key) && !StringUtils.isEmpty(type)){ // 通过类型反查
			HashMap param = new HashMap();
			param.put("typeName", type);
			DataDictType typeDO = dictTypeService.selectOne(param);
			if(typeDO == null){
				return new ResultEntity("","无此字典类型，请添加","");
			}
			String dictType = typeDO.getId();
			if(!StringUtils.isEmpty(dictType)){
				HashMap param2 = new HashMap();
				param2.put("dictType", dictType);
				param2.put("dictKey", key);
				DataDictItem dictItemDO = dictItemService.selectOne(param2);
				if(dictItemDO != null && !StringUtils.isEmpty(dictItemDO.getId())){
					HashMap param3 = new HashMap();
					param3.put("dictType", dictItemDO.getId());
					return new ResultEntity("","OK",dictItemService.list(param3));
				}else {
					return new ResultEntity("","fail");
				}
			}else {
				return new ResultEntity("","fail");
			}
		}else {
			return new ResultEntity("","fail");
		}
	}
	
	/**
	 * 
	 * TODO(简述该方法的作用)根据字典类型名称获取字典值
	 * @method getDicts
	 * @return ResultEntity
	 * @return
	 */
	@APCOSApiOperation(value = "根据字典类型名称获取字典值", developers = {"lingnan"}, description = "根据字典类型名称获取字典值",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/dicts/id")
	public ResultEntity getDictsByType(String dictId) {
		return new ResultEntity("","OK",dictItemService.selectByKey(dictId));
	}

	/**
	 * TODO(简述该方法的作用)根据字典类型id获取字典值
	 * @param typeId
	 * @return
	 */
	@APCOSApiOperation(value = "根据字典类型id获取字典值", developers = {"lingnan"}, description = "根据字典类型id获取字典值",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/dicts/typeId")
	public ResultEntity getDictsByTypeId(String typeId) {
		HashMap param = new HashMap();
		param.put("dictType", typeId);
		int count = dictItemService.listPageCount(param);
		return new ResultEntity("","OK",count);
	}

	@APCOSApiOperation(value = "分页查询字典项", developers = {"lingnan"}, description = "分页查询字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("/cddatadict/dicts/getItems")
	public Map<String,Object> getDictsByTypeId2(String typeId, @RequestParam long page, @RequestParam long limit){
		Map<String,Object> resultMap = new HashMap<>();
		HashMap param = new HashMap();
		param.put("dictType", typeId);
		param.put("page", page);
		param.put("limit", limit);
		resultMap.put("code",0);
		resultMap.put("msg","");
		resultMap.put("count",dictItemService.listPageCount(param));
		resultMap.put("data",dictItemService.listPage(param));
		return resultMap;
	}

	@APCOSApiOperation(value = "查询字典项", developers = {"lingnan"}, description = "查询字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/dicts/getItems2")
	public Map<String,Object> queryDictsByTypeId(String typeId){
		Map<String,Object> resultMap = new HashMap<>();
		HashMap param = new HashMap();
		param.put("dictType", typeId);
		resultMap.put("code",0);
		resultMap.put("msg","");
		List<DataDictItem> list = dictItemService.list(param);
		resultMap.put("count", list.size());
		resultMap.put("data", list);
		return resultMap;
	}
	
	/**
	 * 
	 * TODO(简述该方法的作用)添加字典類型值
	 * @method addDicts
	 * @return ResultEntity
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	@APCOSApiOperation(value = "添加字典类型值", developers = {"lingnan"}, description = "添加字典类型值",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("cddatadict/dicts/add")
	public ResultEntity addDicts(DataDictItem dto) throws Exception {
		//前端校驗新增內容是否存在
		HashMap param = new HashMap();
		param.put("dictType", dto.getDictType());
		List<DataDictItem> resultEntitys = dictItemService.list(param);
		for(DataDictItem oneEntity : resultEntitys) {
			if(oneEntity.getDictName().equals(dto.getDictName())) {
				return new ResultEntity("","nameIsExist");
			}
			if(oneEntity.getDictKey().equals(dto.getDictKey())) {
				return new ResultEntity("","keyIsExist");
			}
		}
		
		DataDictItem entity = new DataDictItem();
		BeanUtils.copyProperties(dto,entity); // src -> tar
		entity.setId(idWorker.nextId()+"");
		entity.setEnableItem("yes");
		entity.setCreateTime(LocalDateTime.now());
		dictItemService.insert(entity);
		return new ResultEntity("","OK");
	}

	@APCOSApiOperation(value = "更新字典项", developers = {"lingnan"}, description = "更新字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("cddatadict/dicts/update")
	public ResultEntity updateDicts(DataDictItem dto) throws Exception {
		//校驗更新內容是否存在
		HashMap param = new HashMap();
		param.put("dictType", dto.getDictType());
		List<DataDictItem> resultEntitys = dictItemService.list(param);
		for(DataDictItem oneEntity : resultEntitys) {
			if(oneEntity.getDictName().equals(dto.getDictName()) && !oneEntity.getId().equals(dto.getId())) {
				return new ResultEntity("","nameIsExist");
			}
			if(oneEntity.getDictKey().equals(dto.getDictKey()) && !oneEntity.getId().equals(dto.getId())) {
				return new ResultEntity("","keyIsExist");
			}
		}
		
		DataDictItem entity = new DataDictItem();
		BeanUtils.copyProperties(dto,entity);
		entity.setUpdateTime(LocalDateTime.now());
		dictItemService.updateByKey(entity);
		return new ResultEntity("","OK");
	}

	@APCOSApiOperation(value = "删除字典项", developers = {"lingnan"}, description = "删除字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("cddatadict/dicts/delete")
	public ResultEntity deleteDicts(String dictId) {
		if(StringUtils.isEmpty(dictId)){
			return new ResultEntity("","字典id不存在");
		}
		HashMap param = new HashMap();
		param.put("dictType",dictId);
		int count = dictItemService.listPageCount(param);
		if(count > 0){
			return new ResultEntity("","该字典项存在下级字典");
		}
		dictItemService.deleteByKey(dictId);
		return new ResultEntity("","OK");
	}

	@APCOSApiOperation(value = "获取所有字典项", developers = {"lingnan"}, description = "获取所有字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@GetMapping("/cddatadict/getAllItem")
	public ResultEntity getAllItem(){
		return new ResultEntity("","OK",dictItemService.list(new HashMap()));
	}

	@APCOSApiOperation(value = "批量删除字典项", developers = {"lingnan"}, description = "批量删除字典项",
			infType = APCOSApiConstans.INF_TYPE_OTHER, infCategory = APCOSApiConstans.INF_CATEGORY_WEB)
	@PostMapping("/cddatadict/batchDelItem")
	public JsonResult batchDelItem(@RequestBody List<DataDictItem> records){
		return dictItemService.batchDelItem(records);
	}
}
